package com.book.auth.handler;

import com.alibaba.fastjson.JSON;
import com.book.core.mode.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证提交异常，或者匿名（未认证）访问受限资源异常
 *
 * @author hongmizfb
 * @date 2025/05/09
 */
@Component
@Slf4j
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_OK);
        String s = "";
        if (authException instanceof BadCredentialsException) {
            s = JSON.toJSONString(R.err(403,"用户名或密码错误"));
            log.error("用户名或密码错误", authException);
        } else if (authException instanceof InternalAuthenticationServiceException) {
            log.error("用户名为空", authException);
            s = JSON.toJSONString(R.err(403, "用户名或密码错误，验证失败！"));
        } else {
            log.error("用户无访问权限", authException);
            s = JSON.toJSONString(R.err(403, "匿名用户不能访问该资源"));
        }
        response.getWriter().write(s);
    }
}
